#include <QDebug>
#include <QList>
#include "SudokuMW.h"
#include "DataManager.h"

SudokuMW::SudokuMW(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(this)
    , m_gridGroup(new QGridLayout[9])
{
    initialize();
}

SudokuMW::~SudokuMW()
{
    if (NULL != m_gridGroup) {
        delete [] m_gridGroup;
    }
}

void SudokuMW::initialize()
{
    initMaps();
    initGroup();
}

void SudokuMW::initMaps()
{
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9; ++j) {
            QString test = DataManager::inst()->getString(i, j);
            m_button[i][j].setText(test);
            m_button[i][j].setFixedSize(60, 60);
        }
    }
}

void SudokuMW::initGroup()
{
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                mySudoItem *item = &m_button[j + (i/3)*3][k + (i%3)*3];
                item->setPoint(j, k, i);
                connect(item, SIGNAL(valueChanged(myPoint)), this, SLOT(onItemValueChanged(myPoint)));
                m_gridGroup[i].addWidget(item, j, k);
            }
        }
        m_mainLayout.addLayout(&m_gridGroup[i], i/3, i%3);
    }
}

void SudokuMW::resetMap()
{
    initMaps();
}

void SudokuMW::autoFill()
{
    DataManager::inst()->autoFillBlanks();
}

void SudokuMW::onItemValueChanged(myPoint point)
{
    printf("your item at position(%d, %d), group %d, value is changed!\n", point.x(), point.y(), point.group());
    fflush(stdout);
}
